import React from "react";

//导入走马灯组件
import {Carousel, Flex} from 'antd-mobile';
//引入发送请求组件axios
import axios from 'axios';
//导入导航菜单图片
import Nav1 from '../../assets/images/nav-1.png'
import Nav2 from '../../assets/images/nav-2.png'
import Nav3 from '../../assets/images/nav-3.png'
import Nav4 from '../../assets/images/nav-4.png'
//导入对应的css文件
import "./index.css"

const flex =[
    {
        id:1,
        img:Nav1,
        title:"整租",
        path:"/home/houseList"

    },
    {
        id:2,
        img:Nav2,
        title:"合租",
        path:"/home/houseList"

    },
    {
        id:3,
        img:Nav3,
        title:"地图找房",
        path:"/home/map"

    },
    {
        id:4,
        img:Nav4,
        title:"去出租",
        path:"/home/houseList"

    }
]
export default class Index extends React.Component{
    /*轮播图不会自动播放，并且路由跳转回来后高度出现问题*/
    //原因是轮播图是动态加载的，加载完成前后轮播图数量不一致
    /*解决办法
    *1 在state中添加状态表示轮播图加载完成
    *2 轮播图加载完成后修改状态为true
    *3 只有轮播图数据加载完成的情况下，才渲染轮播图主件 */
    state = {
        swipers: [],
        isSwiperLoading:false
    }
    async getSwipers() {
        const res = await axios.get("http://localhost:8080/home/swiper")
        this.setState(() => {
            return {
                swipers:res.data.body,
                isSwiperLoading:true
            }
        })
    }
    componentDidMount() {
       this.getSwipers()
    }
    //渲染轮播图数据的方法
    renderSwipers(){
       return  this.state.swipers.map(item => (
            <a
                key={item.id}
                href="http://itcast.cn"
                style={{ display: 'inline-block', width: '100%', height: 212 }}
            >
                <img
                    src={`http://localhost:8080${item.imgSrc}`}
                    alt=""
                    style={{ width: '100%', verticalAlign: 'top' }}
                />
            </a>
        ))
    }

    //导航菜单渲染
    renderFlex(){
        return flex.map(item => <Flex.Item key={item.id} onClick={()=>this.props.history.push(item.path)}>
            <img src={item.img} alt=""/>
            <h2>{item.title}</h2>
        </Flex.Item>)
    }
    render() {
        return (
            <div>
                {this.state.isSwiperLoading? (<Carousel className="swiper"
                    autoplay={true}
                    infinite
                    autoplayInterval={2000}
                >
                    {this.renderSwipers()}
                </Carousel>):("")}
                <Flex className="nav">
                    {this.renderFlex()}
                </Flex>
            </div>
        );
    }
}